package com.xhwl.centiotdata.suppliersystem.mili;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.MiLiConstant;
import com.xhwl.centiotdata.pojo.constant.MiLiYunConstant;
import com.xhwl.centiotdata.pojo.dto.mili.DeviceMiLiYunDTO;
import com.xhwl.centiotdata.pojo.dto.mili.LoginMiLiDTO;
import com.xhwl.centiotdata.pojo.dto.mili.TalkLogDTO;
import com.xhwl.centiotdata.pojo.dto.talkback.TalkBackIntegrationConfigDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: wuyuhao
 * @createDate: 2022/10/31 14:37
 */
@Service
@Slf4j
public class TalkBackMiLiHandler {

    @Autowired
    private GeneralMiLiHandler generalMiLiHandler;

    public String getToken(JSONObject talk) {
        String host = talk.getString("url");
        String appId = talk.getString("appId");
        String appSecret = talk.getString("appSecret");
        int type = 3;
        long timestamp = System.currentTimeMillis() / 1000;
        String verify = GeneralMiLiHandler.MD5(timestamp + "|" + type + "|" + appSecret);
        String Authorization = "Basic " + Base64Utils.encodeToString((appId + ":" + timestamp + ":" + verify + ":" + ":" + type).getBytes());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", Authorization);
        headers.add("appid", appId);
        headers.add("timestamp", String.valueOf(timestamp));
        headers.add("verify", verify);
        headers.add("type", String.valueOf(type));
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> resEntity = restTemplate.exchange(host + MiLiYunConstant.WUYE_CONFIG_URL, HttpMethod.GET, requestEntity, String.class);
        JSONObject res = JSON.parseObject(resEntity.getBody());
        JSONObject body = res.getJSONObject("body");
        return body.getString("token");
    }

    public List<DeviceMiLiYunDTO> getDeviceList(JSONObject talk, String token) {
        String host = talk.getString("url");
        String appId = talk.getString("appId");
        String appSecret = talk.getString("appSecret");
        String communityId = talk.getString("communityId");
        int type = 3;
        long timestamp = System.currentTimeMillis() / 1000;
        String verify = GeneralMiLiHandler.MD5(timestamp + "|" + type + "|" + appSecret);
        String Authorization = "Basic " + Base64Utils.encodeToString((appId + ":" + timestamp + ":" + verify + ":" + token + ":" + type).getBytes());

        MultiValueMap<String, Object> reqBody = new LinkedMultiValueMap<>();
        reqBody.add("service_id", "7");
        reqBody.add("page", "1");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", Authorization);
        headers.add("appid", appId);
        headers.add("timestamp", String.valueOf(timestamp));
        headers.add("verify", verify);
        headers.add("token", token);
        headers.add("type", String.valueOf(type));
        HttpEntity<Object> requestEntity = new HttpEntity<>(reqBody, headers);
        String url = "/1.1/wuye/community/" + communityId + "/device/page";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> resEntity = restTemplate.exchange(host + url, HttpMethod.POST, requestEntity, String.class);
        JSONObject res = JSON.parseObject(resEntity.getBody());
        JSONObject body = res.getJSONObject("body");
        String item = body.getString("item");
        return JSON.parseArray(item, DeviceMiLiYunDTO.class);
    }

    public List<TalkLogDTO> queryTalkLog(TalkBackIntegrationConfigDTO configDTO, Map<String, Object> map) {
        LoginMiLiDTO loginInfo = generalMiLiHandler.getLoginInfo(configDTO.getLoginName(),
                configDTO.getPassword(), configDTO.getIpAndPort());
        JSONObject req = new JSONObject(map);
        String response = generalMiLiHandler.doBusinessRequest(configDTO.getLoginName(), loginInfo,
                configDTO.getIpAndPort(), MiLiConstant.TALK_LOG, req);
        JSONObject res = JSON.parseObject(response);
        if (res.getInteger("Result") != 0) {
            log.error("请求url: {}, errMsg: {}", MiLiConstant.TALK_LOG, res.getString("Message"));
            return null;
        }
        JSONObject body = res.getJSONObject("Body");
        JSONArray list = body.getJSONArray("List");
        return list.toJavaList(TalkLogDTO.class);
    }
}
